<template>
  <div class="dashboard-container">
    <!-- 顶部功能栏 -->
    <el-row gutter="20">
      <!-- 用户信息卡片 -->
      <el-col :span="12">
        <el-card class="dashboard-card" shadow="always">
          <!-- 用户信息展示 -->
          <div class="user-info" v-if="userInfo">
            <el-descriptions :column="2" border size="default" :label-style="{ width: '100px' }">
              <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
              <el-descriptions-item label="持卡人姓名">{{ userInfo.cardName }}</el-descriptions-item>
              <el-descriptions-item label="借阅卡号">{{ userInfo.cardNumber }}</el-descriptions-item>
              <el-descriptions-item label="账户状态">
                <el-tag :type="userInfo.status === 1 ? 'success' : 'danger'">
                  {{ userInfo.status === 1 ? '正常' : '禁用' }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
            <el-divider />
            <div id="bookTypeChart" style="width: 100%; height: 200px;"></div>
          </div>
          <div v-else>
            <el-skeleton :rows="4" animated />
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="dashboard-card">
          <el-space :size="10">
            <el-button type="success" @click="dialogVisible = true" :disabled="!userInfo">
              借阅图书
            </el-button>
            <el-button type="primary" @click="fetchUserInfo">刷新用户信息</el-button>
            <el-button type="warning" @click="showPasswordDialog = true" :disabled="!userInfo">
              更新密码
            </el-button>
            <el-button type="danger" @click="logout" :disabled="!userInfo">注销账户</el-button>
          </el-space>
          <el-divider />
          <div id="borrowTimeChart" style="width: 100%; height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 借阅记录卡片 -->
    <el-card class="dashboard-card borrow-records-card">
      <div class="borrow-functions">
        <el-button
            type="danger"
            :disabled="selectedBorrowRecords.length === 0 || !userInfo"
            @click="batchReturnBooks"
        >
          归还图书
        </el-button>
        <el-button
            type="warning"
            :disabled="selectedBorrowRecords.length === 0 || !userInfo"
            @click="batchRenewBooks"
        >
          续借图书
        </el-button>
      </div>
      <el-table
          v-if="borrowRecords.length"
          :data="borrowRecords"
          style="width: 100%"
          height="400"
          row-key="borrowId"
          @selection-change="handleSelectionChange"
          default-sort="{ prop: 'borrowDate', order: 'descending' }"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" />
        <el-table-column prop="bookNumber" label="书籍编号" width="120" />
        <el-table-column prop="bookName" label="图书名称" width="180" />
        <el-table-column prop="bookType" label="图书类型" width="120" />
        <el-table-column prop="borrowDate" label="借阅时间" width="180" sortable />
        <el-table-column prop="closeDate" label="归还时间" width="180" sortable />
        <el-table-column prop="borrowing" label="借阅状态" sortable>
          <template #default="scope">
            <el-tag :type="scope.row.borrowing === 1 ? 'danger' : 'success'">
              {{ scope.row.borrowing === 1 ? '借阅中' : '借阅结束' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div v-else>
        <el-empty description="暂无借阅记录" />
      </div>
    </el-card>

    <!-- 更新密码弹窗 -->
    <el-dialog title="更新密码" v-model="showPasswordDialog">
      <el-form :model="passwordForm">
        <el-form-item label="当前密码" required>
          <el-input v-model="passwordForm.currentPassword" type="password" placeholder="输入当前密码" />
        </el-form-item>
        <el-form-item label="新密码" required>
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="输入新密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updatePassword">提交</el-button>
          <el-button @click="showPasswordDialog = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 借阅图书弹窗 -->
    <el-dialog title="借阅图书" v-model="dialogVisible">
      <el-form :model="borrowForm">
        <el-form-item label="书籍编号" required>
          <el-input v-model="borrowForm.bookNumber" placeholder="输入书籍编号" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="borrowBook">借阅</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'; // 添加 watch
import { ElMessage, ElMessageBox } from 'element-plus';
import http from '../utils/axios';
import * as echarts from 'echarts'; // 引入 echarts

// 数据与状态
const userInfo = ref(null);
const borrowRecords = ref([]);
const selectedBorrowRecords = ref([]);
const passwordForm = ref({ currentPassword: '', newPassword: '' });
const borrowForm = ref({ bookNumber: '' });
const dialogVisible = ref(false);
const showPasswordDialog = ref(false);
const bookTypeChart = ref(null);
const borrowTimeChart = ref(null);
const bookTypeData = ref([]);
const borrowTimeData = ref([]);

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await http.post('/user/getUserInfo', {
      username: localStorage.getItem('username'),
      cardNumber: localStorage.getItem('cardNumber'),
    });
    if (response.status) {
      userInfo.value = response.data;
      localStorage.setItem('userId', response.data.userId); // 保存userId
      ElMessage.success('用户信息获取成功');
    } else {
      ElMessage.error(response.data || '获取用户信息失败');
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败：' + error.message);
  }
};

// 借阅书籍
const borrowBook = async () => {
  try {
    const { cardNumber } = userInfo.value;
    const { bookNumber } = borrowForm.value;
    if (!bookNumber) {
      ElMessage.error('请输入书籍编号');
      return;
    }
    const response = await http.post('/borrow/lend', { cardNumber, bookNumber });
    if (response.status) {
      ElMessage.success('借阅成功');
      dialogVisible.value = false;
      await fetchBorrowRecords(); // 更新借阅记录
    } else {
      ElMessage.error(response.data || '借阅失败');
    }
  } catch (error) {
    ElMessage.error('借阅失败：' + error.message);
  }
};

// 获取借阅记录
const fetchBorrowRecords = async () => {
  try {
    const response = await http.get(`/borrow/${localStorage.getItem('cardNumber')}`);
    if (response.status) {
      const records = response.data || [];
      const bookNumbers = records.map(record => record.bookNumber);
      const bookDetails = await Promise.all(
        bookNumbers.map(bookNumber => http.get(`/book/${bookNumber}`))
      );
      const bookMap = new Map(bookDetails.map(detail => [detail.data.bookNumber, detail.data]));
      records.forEach(record => {
        record.bookName = bookMap.get(record.bookNumber)?.bookName || '未知';
        record.bookType = bookMap.get(record.bookNumber)?.bookType || '未知';
      });
      borrowRecords.value = records;
      ElMessage.success('借阅记录加载成功');
      updateBookTypeStatistics(records);
      updateBorrowTimeStatistics(records);
    } else {
      ElMessage.error(response.data || '加载借阅记录失败');
    }
  } catch (error) {
    ElMessage.error('加载借阅记录失败：' + error.message);
  }
};

// 统计图书类型
const updateBookTypeStatistics = (records) => {
  const typeCount = {};
  records.forEach(record => {
    const type = record.bookType;
    if (typeCount[type]) {
      typeCount[type]++;
    } else {
      typeCount[type] = 1;
    }
  });
  bookTypeData.value = Object.keys(typeCount).map(type => ({
    name: type,
    value: typeCount[type]
  }));
  nextTick(() => {
    if (bookTypeChart.value) {
      bookTypeChart.value.setOption({
        series: [
          {
            data: bookTypeData.value
          }
        ]
      });
    }
  });
};

// 统计借阅时间
const updateBorrowTimeStatistics = (records) => {
  const timeCount = {};
  records.forEach(record => {
    const date = new Date(record.borrowDate);
    const year = date.getFullYear();
    const month = date.getMonth() + 1; // 月份从0开始
    const key = `${year}-${month}`;
    if (timeCount[key]) {
      timeCount[key]++;
    } else {
      timeCount[key] = 1;
    }
  });
  const sortedKeys = Object.keys(timeCount).sort();
  borrowTimeData.value = sortedKeys.map(key => ({
    name: key,
    value: timeCount[key]
  }));
  nextTick(() => {
    if (borrowTimeChart.value) {
      borrowTimeChart.value.setOption({
        xAxis: {
          data: borrowTimeData.value.map(item => item.name)
        },
        series: [
          {
            data: borrowTimeData.value.map(item => item.value)
          }
        ]
      });
    }
  });
};

// 批量归还书籍
const batchReturnBooks = async () => {
  try {
    const borrowIds = selectedBorrowRecords.value.map((record) => record.borrowId);
    await ElMessageBox.confirm("确认归还选中的图书？", "提示", {
      confirmButtonText: "归还",
      cancelButtonText: "取消",
      type: "warning",
    });
    const response = await Promise.all(
      borrowIds.map((borrowId) => http.put(`/borrow/return/${borrowId}`))
    );
    const successCount = response.filter((res) => res.status).length;
    ElMessage.success(`成功归还 ${successCount} 本图书`);
    await fetchBorrowRecords();
  } catch (error) {
    ElMessage.error("归还失败：" + error.message);
  }
};

// 批量续借书籍
const batchRenewBooks = async () => {
  try {
    const borrowIds = selectedBorrowRecords.value.map((record) => record.borrowId);
    await ElMessageBox.confirm("确认续借选中的图书？", "提示", {
      confirmButtonText: "续借",
      cancelButtonText: "取消",
      type: "warning",
    });
    const responses = await Promise.all(
      borrowIds.map((borrowId) => http.put(`/borrow/renew/${borrowId}`))
    );
    const successCount = responses.filter((res) => res.status).length;
    if (successCount === borrowIds.length) {
      ElMessage.success(`成功续借 ${successCount} 本图书`);
    } else {
      ElMessage.error(`续借失败：${borrowIds.length - successCount} 本图书续借失败`);
    }
    await fetchBorrowRecords();
  } catch (error) {
    ElMessage.error("续借失败：" + error.message);
  }
};

// 更新密码
const updatePassword = async () => {
  try {
    const { currentPassword, newPassword } = passwordForm.value;
    if (!currentPassword || !newPassword) {
      ElMessage.error('当前密码和新密码均不能为空');
      return;
    }
    const response = await http.put('/user/update/validate_password', {
      userId: userInfo.value?.userId,
      currentPassword,
      newPassword,
    });
    if (response.status) {
      ElMessage.success(response.data || '密码更新成功');
      passwordForm.value.currentPassword = '';
      passwordForm.value.newPassword = '';
      showPasswordDialog.value = false;
    } else {
      ElMessage.error(response.data || '密码更新失败');
    }
  } catch (error) {
    ElMessage.error('密码更新失败：' + error.message);
  }
};

// 注销账户
const logout = async () => {
  try {
    await ElMessageBox.confirm('确定注销账户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    const response = await http.delete(`/user/delete/${userInfo.value?.userId}`);
    if (response.status) {
      ElMessage.success('账户已注销');
      localStorage.clear();
      window.location.href = '/login';
    } else {
      ElMessage.error(response.data || '注销失败');
    }
  } catch (error) {
    ElMessage.error('注销失败：' + error.message);
  }
};

// 处理选中的借阅记录
const handleSelectionChange = (val) => {
  selectedBorrowRecords.value = val;
};

const initCharts = () => {
  // 初始化借阅时间图表
  borrowTimeChart.value = echarts.init(document.getElementById('borrowTimeChart'));
  borrowTimeChart.value.setOption({
    title: {
      text: '借阅时间统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: borrowTimeData.value.map(item => item.name)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: borrowTimeData.value.map(item => item.value),
        type: 'line'
      }
    ]
  });
};

const initBookTypeChart = () => {
  // 初始化图书类型图表
  bookTypeChart.value = echarts.init(document.getElementById('bookTypeChart'));
  bookTypeChart.value.setOption({
    title: {
      text: '图书类型统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '图书类型',
        type: 'pie',
        radius: '50%',
        data: bookTypeData.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  });
};

// 页面加载时获取用户信息和借阅记录
onMounted(() => {
  fetchUserInfo();
  fetchBorrowRecords().then(() => {
    nextTick(() => {
      initCharts();
      initBookTypeChart();
    });
  });
});
</script>


<style scoped>
.dashboard-container {
  padding: 20px;
}

.dashboard-card {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  height: 100%; /* 确保卡片高度一致 */
}

.borrow-functions {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px; /* 添加间距 */
}

.borrow-records-card {
  margin-top: 20px;
}

.user-details p {
  margin: 5px 0;
}
</style>

